import string
from selenium import webdriver
from selenium.webdriver.common.by import By

# from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import yaml


# 从yaml配置文件中读取站点信息
config = {}
with open("./config.yaml", "r", encoding="utf-8") as f:
    config = yaml.load(f.read(), Loader=yaml.FullLoader)


# 自定义edge选项, 执行结束后不自动关闭浏览器窗口
options = webdriver.EdgeOptions()
options.accept_insecure_certs = True
options.binary_location = config["browser_path"]
options.add_experimental_option("detach", True)

driver = webdriver.Edge(options=options)


# 自动登录函数, 传入参数为(网址, 是否新标签打开, 用户输入框css选择器, 密码框css选择器, 用户名, 密码, 登录按钮选择器)
def auto_login(
    url: string,
    use_tab: bool,
    user_selector: string,
    pass_selector: string,
    username: string,
    password: string,
    login_selector: string,
):
    if use_tab:
        driver.switch_to.new_window("tab")
        driver.get(url)
    else:
        driver.get(url)
    wait = WebDriverWait(driver, timeout=config["load_timeout"])

    user_box = wait.until(
        expected_conditions.visibility_of_element_located(
            (By.CSS_SELECTOR,
            user_selector)
        )
    )
    user_box.send_keys(username)
    pass_box = wait.until(
        expected_conditions.visibility_of_element_located(
            (By.CSS_SELECTOR,
            pass_selector)
        )
    )
    pass_box.send_keys(password)
    login_btn = driver.find_element(
        By.CSS_SELECTOR,
        login_selector,
    )
    login_btn.click()


# 不使用新建标签
def login_without_tab(template, site):
    auto_login(
        site["url"],
        False,
        template["user_selector"],
        template["pass_selector"],
        site["username"],
        site["password"],
        template["login_selector"],
    )


# 使用新建标签
def login_use_tab(template, site):
    auto_login(
        site["url"],
        True,
        template["user_selector"],
        template["pass_selector"],
        site["username"],
        site["password"],
        template["login_selector"],
    )


# 读取配置文件中的网站信息, 第一个网站不适用新建标签, 之后的网站使用新建标签
if len(config["templates"]) >= 1 and len(config["templates"][0]["sites_info"]) >= 1:
    login_without_tab(config["templates"][0], config["templates"][0]["sites_info"][0])

    if len(config["templates"][0]["sites_info"]) > 1:
        for site in config["templates"][0]["sites_info"][1:]:
            login_use_tab(config["templates"][0], site)
        if len(config["templates"]) > 1:
            for template in config["templates"][1:]:
                if len(template["sites_info"]) >= 1:
                    for site in template["sites_info"]:
                        login_use_tab(template, site)
else:
    print("配置文件站点信息不完整, 请检查")
